<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams" ref="queryFormRef">
        <el-form-item label="楼号" prop="buildingNo">
          <el-input
            v-model="queryParams.buildingNo"
            placeholder="请输入楼号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="单元号" prop="unitNo">
          <el-input
            v-model="queryParams.unitNo"
            placeholder="请输入单元号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="房间号" prop="roomNo">
          <el-input
            v-model="queryParams.roomNo"
            placeholder="请输入房间号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            style="width: 200px"
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="item in houseStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <el-button type="primary" :icon="Plus" @click="handleAdd"
            >新增房屋</el-button
          >
          <!-- <el-button type="success" :icon="Upload" @click="handleImport"
						>批量导入</el-button
					> -->
          <!-- <el-button type="warning" :icon="Download" @click="handleExport"
            >导出数据</el-button
          > -->
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="houseList"
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="房屋信息" min-width="180">
          <template #default="{ row }">
            {{ `${row.buildingNo}栋${row.unitNo}单元${row.roomNo}室` }}
          </template>
        </el-table-column>
        <el-table-column
          prop="area"
          label="面积(㎡)"
          width="100"
          align="center"
        />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="业主信息" min-width="180">
          <template #default="{ row }">
            <template v-if="row.owner">
              {{ row.owner.name }}
              <el-tag size="small" type="info" class="ml-2">
                {{ row.owner.phone }}
              </el-tag>
            </template>
            <span v-else>暂无业主</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdAt"
          label="创建时间"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Edit" @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button
              type="success"
              link
              :icon="User"
              @click="handleAssignOwner(row)"
              >分配业主</el-button
            >
            <el-button
              type="warning"
              link
              :icon="SetUp"
              @click="handleUpdateStatus(row)"
              >修改状态</el-button
            >
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNumber"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 状态修改对话框 -->
    <el-dialog
      v-model="statusDialog.visible"
      title="修改房屋状态"
      width="500px"
    >
      <el-form :model="statusDialog.form" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(statusDialog.form.oldStatus)">
            {{ getStatusLabel(statusDialog.form.oldStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select
            v-model="statusDialog.form.status"
            placeholder="请选择新状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in houseStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmUpdateStatus"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 业主分配对话框 -->
    <el-dialog v-model="ownerDialog.visible" title="分配业主" width="500px">
      <el-form :model="ownerDialog.form" label-width="100px">
        <el-form-item label="当前业主">
          <span v-if="ownerDialog.form.currentOwner">
            {{ ownerDialog.form.currentOwner.name }}
            ({{ ownerDialog.form.currentOwner.phone }})
          </span>
          <span v-else>暂无业主</span>
        </el-form-item>
        <el-form-item label="新业主">
          <el-select
            v-model="ownerDialog.form.ownerId"
            placeholder="请选择业主"
            filterable
            remote
            :remote-method="handleOwnerSearch"
            :loading="ownerDialog.loading"
            style="width: 100%"
          >
            <el-option
              v-for="item in ownerDialog.options"
              :key="item.id"
              :label="`${item.name} (${item.phone})`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ownerDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmAssignOwner">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete,
  Upload,
  Download,
  User,
  SetUp,
} from "@element-plus/icons-vue";
import {
  getHouses,
  deleteHouse,
  updateHouseStatus,
  updateHouse,
} from "@/api/house";
import { getResidents } from "@/api/resident";

const router = useRouter();

// 房屋状态选项
const houseStatusOptions = [
  { value: "Empty", label: "空置" },
  { value: "Occupied", label: "已入住" },
  { value: "Rented", label: "已出租" },
  { value: "Sold", label: "已售出" },
  { value: "Maintained", label: "维修中" },
];

// 查询参数
const queryParams = ref({
  buildingNo: "",
  unitNo: "",
  roomNo: "",
  status: "",
  pageNumber: 1,
  pageSize: 10,
});

// 数据相关
const loading = ref(false);
const houseList = ref([]);
const total = ref(0);
const queryFormRef = ref();

// 状态修改对话框
const statusDialog = reactive({
  visible: false,
  form: {
    id: null,
    oldStatus: "",
    status: "",
  },
});

// 业主分配对话框
const ownerDialog = reactive({
  visible: false,
  loading: false,
  form: {
    id: null,
    currentOwner: null,
    ownerId: null,
  },
  options: [],
});

// 获取房屋列表
const getList = async () => {
  try {
    loading.value = true;
    const res = await getHouses(queryParams.value);
    houseList.value = res.items;
    total.value = res.total;
  } catch (error) {
    console.error("获取房屋列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleQuery = () => {
  queryParams.value.pageNumber = 1;
  getList();
};

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 新增房屋
const handleAdd = () => {
  router.push("/house/add");
};

// 编辑房屋
const handleEdit = (row) => {
  router.push(`/house/edit/${row.id}`);
};

// 删除房屋
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除房屋 ${row.buildingNo}栋${row.unitNo}单元${row.roomNo}室 吗？`,
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    try {
      await deleteHouse(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      console.error("删除失败：", error);
    }
  });
};

// 修改状态
const handleUpdateStatus = (row) => {
  statusDialog.form = {
    id: row.id,
    oldStatus: row.status,
    status: row.status,
  };
  statusDialog.visible = true;
};

// 确认修改状态
const confirmUpdateStatus = async () => {
  try {
    await updateHouseStatus(statusDialog.form.id, {
      status: statusDialog.form.status,
    });
    ElMessage.success("状态修改成功");
    statusDialog.visible = false;
    getList();
  } catch (error) {
    console.error("修改状态失败：", error);
  }
};

// 分配业主
const handleAssignOwner = (row) => {
  ownerDialog.form = {
    id: row.id,
    currentOwner: row.owner,
    ownerId: row.ownerId,
    ...row,
  };
  ownerDialog.visible = true;
};

// 搜索业主
const handleOwnerSearch = async (query) => {
  if (query) {
    try {
      ownerDialog.loading = true;
      const res = await getResidents({ name: query, pageSize: 100 });
      ownerDialog.options = res.items;
    } catch (error) {
      console.error("搜索业主失败：", error);
    } finally {
      ownerDialog.loading = false;
    }
  } else {
    ownerDialog.options = [];
  }
};

// 确认分配业主
const confirmAssignOwner = async () => {
  try {
    await updateHouse(ownerDialog.form.id, ownerDialog.form);
    ElMessage.success("业主分配成功");
    ownerDialog.visible = false;
    getList();
  } catch (error) {
    console.error("分配业主失败：", error);
  }
};

// 导入导出
const handleImport = () => {
  ElMessage.info("功能开发中");
};

const handleExport = () => {
  ElMessage.info("功能开发中");
};

// 状态标签样式
const getStatusType = (status) => {
  const map = {
    Empty: "info",
    Occupied: "success",
    Rented: "warning",
    Sold: "primary",
    Maintained: "danger",
  };
  return map[status] || "info";
};

const getStatusLabel = (status) => {
  const option = houseStatusOptions.find((item) => item.value === status);
  return option ? option.label : status;
};

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return "";
  return new Date(date).toLocaleString();
};

// 分页方法
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
};

const handleCurrentChange = (val) => {
  queryParams.value.pageNumber = val;
  getList();
};

// 初始化
onMounted(async () => {
  await getList();
  ownerDialog.loading = true;
  const res = await getResidents({ pageSize: 100 });
  ownerDialog.options = res.items;
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .card-header {
      display: flex;
      gap: 10px;
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .ml-2 {
    margin-left: 8px;
  }
}
</style>
